package com.service.impl;

import com.dao.BaseDAO;
import com.model.User;
import com.service.UserManager;
import org.apache.log4j.Logger;

import java.util.BitSet;
import java.util.List;
import java.util.Map;


/**
 * Created by zhanghf on 2015/6/26.
 */

public class UserManagerImpl implements UserManager {
    /**
     * Loger4j的logger
     */
    private static final Logger logger = Logger.getLogger(UserManagerImpl.class);

    private static  BaseDAO dao = new BaseDAO();

    @Override
    public long createUser(User user) {
        User newUser = null;
        if (dao.add(user)){
            newUser = getUserByName(user.getUsername());
            if (newUser == null){
                return 0L;
            }
        }
        return newUser.getId();
    }

    @Override
    public List<User> getUser(Map<String,String> mapUser){
        String sql = "from User u where ";
        String sqlext = "";
        for(Map.Entry<String,String> entry : mapUser.entrySet()){
            String strkey = entry.getKey();
            String strval = entry.getValue();
            if (sqlext == ""){
                sqlext += "u." + strkey + "=" + strval;
            }
            else {
                sqlext +=  " and u." + strkey + "=" + strval;
            }
        }
        sql += sqlext;
        dao.query(sql, null);
        return null;
    }

    @Override
    public boolean modifyUser(User user) {
        return dao.update(user);
    }

    @Override
    public boolean delUser(long id) {
        User user = new User();
        user.setId(id);
        boolean result = false;
        try {
            result = dao.delete(user);
        } catch (Exception e) {
            logger.error("delUserById error");
        }
        return dao.delete(user);
    }

    @Override
    public boolean delUser(long[] id) {
        boolean result = false;
        try {
            result = dao.delete("user", id);
        } catch (Exception e) {
            logger.error("delUserById error");
        }
        return result;
    }

    @Override
    public User getUserById(long id) {
        return (User)dao.get(User.class, id);
    }

    @Override
    public User getUserByName(String name) {
        String[] para ={name};
        User user = (User)dao.queryOne("from User u where u.username=?", para);
        if (user == null){
            logger.info("can not get user where username=" + name);
            return null;
        }
        return user;
    }
}
